<template>
  <div class="ele-body">
    <el-card shadow="never">
      <el-form
          :model="where"
          label-width="77px"
          class="ele-form-search"
          @keyup.enter.native="reload"
          @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="4" :md="8">
            <el-form-item label="异常编号:">
              <el-input
                  clearable
                  v-model="where.operation_no"
                  placeholder="请输入异常编号"/>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="8">
            <el-form-item label="所属单位:">
              <organization-select v-model="where.organization_id" :model_type="type"></organization-select>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="8">
            <el-form-item label="上报用户:">
              <el-input
                  clearable
                  v-model="where.create_user"
                  placeholder="请输入上报用户"/>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="8">
            <el-form-item label="作业类别:">
              <operation-category-select v-model="where.operation_category"></operation-category-select>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="8">
            <el-form-item label="巡查分类:">
              <exception-category-select :type="type" :unit="where.organization_id"
                                         v-model="where.exception_category"></exception-category-select>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="8">
            <el-form-item label="是否单位可见:">
              <el-select
                  clearable
                  v-model="where.organization_show"
                  placeholder="请选择单位是否可见"
                  class="ele-fluid">
                <el-option label="可见" value="1"/>
                <el-option label="不可见" value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="8">
            <el-form-item label="是否处罚:">
              <el-select
                  clearable
                  v-model="where.penalty"
                  placeholder="请选择是否处罚"
                  class="ele-fluid">
                <el-option label="是" value="1"/>
                <el-option label="否" value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="异常地址:">
              <el-cascader
                  clearable
                  v-model="where.area_id"
                  class="ele-fluid"
                  placeholder="请选择省市区"
                  :options="regions"
                  popper-class="ele-pop-wrap-higher"/>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="8">
            <el-form-item label="详细地址:">
              <el-input
                  clearable
                  v-model="where.address"
                  placeholder="请输入详细地址"/>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="8">
            <el-date-picker v-model="where.time" style="
										width: 100%;
										height: 35px;
										background: rgba(46, 108, 151, 0.2);
										border: 1px solid #40afff;
									" size="mini" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-col>
          <el-col :lg="4" :md="8">
            <div class="ele-form-actions">
              <el-button
                  type="primary"
                  icon="el-icon-search"
                  class="ele-btn-icon"
                  @click="reload">查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <ele-pro-table
          v-if="columns.length"
          ref="table"
          :where="where"
          :datasource="url"
          :columns="columns"
          :selection.sync="selection"
          :init-load="false"
          height="calc(100vh - 315px)">
        <template slot="toolbar">
          <el-button
              @click="openEdit(null)"
              type="primary"
              icon="el-icon-plus"
              class="ele-btn-icon"
              size="small">添加
          </el-button>
          <!--          v-if="permission.includes('road-traffic:disease:add')"-->
          <el-button
              @click="setShowBatch"
              :disabled="!this.selection.length"
              type="primary"
              icon="el-icon-setting"
              class="ele-btn-icon"
              size="small">设置可见
          </el-button>
          <!--          v-if="permission.includes('road-traffic:disease:setShow')"-->
          <el-button
              @click="removeBatch"
              :disabled="!this.selection.length"
              type="danger"
              icon="el-icon-delete"
              class="ele-btn-icon"
              size="small">删除
          </el-button>
          <!--          v-if="permission.includes('road-traffic:disease:del')"-->


          <el-button v-if="$route.name==='/operation/emergency'" :loading="report_day.loading" @click="report_day_tap()" type="info" class="ele-btn-icon" size="small">日报</el-button>
          <el-button v-if="$route.name==='/operation/emergency'" @click="report_week_tap()" type="info" class="ele-btn-icon" size="small">周报</el-button>

        </template>
        <template slot="organization_show" slot-scope="{row}">
          <div style="display: flex">
            <el-tag
                v-for="(item ,index) in row.organization_show"
                :key="index"
                style="margin-right: 2px"
                :type="['warning', 'success'][item]"
                size="mini">
              {{ ['否', '是'][item] }}
            </el-tag>
          </div>
        </template>
        <template slot="penalty" slot-scope="{row}">
          <div style="display: flex;">
            <el-tag
                v-for="(item,index) in row.penalty"
                :key="index"
                style="margin-right: 2px"
                :type="['warning', 'success'][item]"
                size="mini">
              {{ ['否', '是'][item] }}
            </el-tag>
          </div>
        </template>
        <template slot="is_verify" slot-scope="{row}">
          <div style="display: flex;">
            <el-tag
                v-for="(item,index) in row.is_verify"
                :key="index"
                style="margin-right: 2px"
                :type="['warning', 'success'][item]"
                size="mini">
              {{ ['否', '是'][item] }}
            </el-tag>
          </div>
        </template>
        <!--        v-if="permission.includes('operation:' + type + ':edit')"-->
        <template slot="action" slot-scope="{row}">
          <el-link
              type="primary"
              :underline="false"
              @click="info(row)">打标详情
          </el-link>
          <el-link
              type="primary"
              :underline="false"
              icon="el-icon-edit"
              @click="openEdit(row)">修改
          </el-link>
          <el-popconfirm
              class="ele-action"
              title="确定要删除吗？"
              @confirm="remove(row)">
            <el-link
                type="danger"
                slot="reference"
                :underline="false"
                icon="el-icon-delete">删除
            </el-link>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>

    <el-dialog
        width="80%"
        :visible.sync="dialog.visible"
        :lock-scroll="false"
        custom-class="ele-dialog-form"
        @opened="dialogOpen"
        :title="'异常编码： ' + dialog.no">
      <ele-pro-table
          ref="infoTable"
          :need-page="false"
          :where="{no: dialog.no}"
          :datasource="dialog.url"
          :columns="dialog.columns"
          :init-load="false"
          height="calc(100vh - 315px)">
        <template slot="credential" slot-scope="{row}">
          <viewer :images="row.credential">
            <img v-for="(credential, index) in row.credential" :key="index" width="30px" :src="credential"/>
          </viewer>
        </template>
        <template slot="organization_show" slot-scope="{row}">
          <el-tag
              :type="['warning', 'success'][row.organization_show]"
              size="mini">
            {{ ['否', '是'][row.organization_show] }}
          </el-tag>
        </template>
        <template slot="penalty" slot-scope="{row}">
          <el-tag
              :type="['warning', 'success'][row.penalty]"
              size="mini">
            {{ ['否', '是'][row.penalty] }}
          </el-tag>
        </template>
        <template slot="is_verify" slot-scope="{row}">
          <el-tag
              :type="['warning', 'success'][row.is_verify]"
              size="mini">
            {{ ['否', '是'][row.is_verify] }}
          </el-tag>
        </template>
        <template slot="readUser" slot-scope="{row}">
          <el-tag v-for="(val, key) in row.read_user" :key="key" type="success" size="mini">
            {{ val.realname }}
          </el-tag>
        </template>
        <template slot="action" slot-scope="{row}">
          <el-link
              type="primary"
              :underline="false"
              @click="push(row)">推送
          </el-link>
        </template>
      </ele-pro-table>
      <div slot="footer">
        <el-button @click="dialog.visible = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
        width="300px"
        :visible.sync="pushDialog.visible"
        :lock-scroll="false"
        custom-class="ele-dialog-form"
        :title="'推送消息： ' + current.operation_no">
      <el-checkbox-group v-model="pushDialog.user">
        <el-checkbox v-for="user in verifyUserList" :label="user.id" :key="user.id" :disabled="!user.openid">
          {{ user.realname }}
          <template v-if="!user.openid">(未绑定微信)</template>
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pushDialog.visible = false">取 消</el-button>
        <el-button type="primary" :disabled="!pushDialog.user.length" :loading="pushDialog.loading" @click="pushMsg">确 定</el-button>
      </span>
    </el-dialog>

<!--    :style="{opacity:'0 !important'}"-->
    <el-dialog :visible.sync="report_day.show" title="日报" width="720px" custom-class="ele-dialog-form" :style="{opacity:'0 !important'}">
      <div id="day-pdf" :style="{display:'grid',gap:'22px', color: '#000', background: '#fff'}">
        <div :style="{position:'relative',borderRadius:'4px',overflow:'hidden'}">
          <div class="pdf-bg">
            <div :style="{textAlign:'center',fontSize:'48px',padding:'44px', color: '#000'}">龙华区无人机自动化安全巡查工作日报</div>
            <el-descriptions class="margin-top" :labelStyle="{width: '130px', background: 'rgba(0,0,0,0)', color: '#000', fontWeight: 600}" :column="2" size="small" border>
              <el-descriptions-item>
                <template slot="label">报送时间：</template>
                {{report_day.data.time}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">报送人：</template>
                {{report_day.data.user}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">日常巡查任务数：</template>
                {{report_day.data.times}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">突发事件巡查架次：</template>
                --
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">日巡飞时长：</template>
                {{report_day.data.duration}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">日飞行距离：</template>
                {{report_day.data.distance}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">飞手：</template>
                --
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">天气：</template>
                --
              </el-descriptions-item>
              <el-descriptions-item :span="2">
                <template slot="label">备注：</template>
                {{report_day.data.memo}}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
        <div v-for="(item,index) in report_day.data.items" :key="index" :style="{position:'relative',borderRadius:'4px',overflow:'hidden',display:'grid',gap:'11px'}">
          <div class="pdf-bg">
            <el-descriptions class="margin-top" :labelStyle="{width: '130px', background: 'rgba(0,0,0,0)', color: '#000', fontWeight: 600}" :column="2" size="small" border>
              <el-descriptions-item>
                <template slot="label">{{ index + 1 }} 巡飞场景：</template>
                {{item.scene}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">时间：</template>
                {{item.create_time}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">巡飞位置：</template>
                {{item.address}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">机场：</template>
                --
              </el-descriptions-item>
              <el-descriptions-item :span="2">
                <template slot="label">巡飞总结：</template>
                --
              </el-descriptions-item>
            </el-descriptions>
            <div style="display: flex; margin-top: 2px; justify-content: space-between">
              <img v-for="(item,index) in item.images" :key="index" :src="item" alt="" style="width: 33%;">
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import fs from 'file-saver'
import {mapGetters} from "vuex";
import {regionData} from 'element-china-area-data'
import organizationSelect from '@/components/organizationSelect';
import exceptionCategorySelect from './components/exceptionCategorySelect';
import operationCategorySelect from './components/operationCategorySelect';
import html2pdf from "html2pdf.js";
export default {
  name: 'operation',
  computed: {
    ...mapGetters(['permission'])
  },
  components: {
    organizationSelect,
    exceptionCategorySelect,
    operationCategorySelect
  },
  data() {
    return {
      type: 'way',
      regions: regionData,
      url: '/operation/getList',
      columns: [],
      columnsReset: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center',
          //fixed: "left"
        },
        {
          prop: 'id',
          label: 'ID',
          width: 60,
          align: 'center',
          showOverflowTooltip: true,
          //fixed: "left"
        },
        {
          prop: 'operation_no',
          label: '异常编号',
          align: 'center',
          showOverflowTooltip: true,
          width: 120,
        },
        {
          prop: 'organization_name',
          label: '所属单位',
          align: 'center',
          showOverflowTooltip: true,
          width: 100,
        },
        {
          prop: 'operation_category_name',
          label: '作业类别',
          align: 'center',
          showOverflowTooltip: true,
          width: 100
        },
        {
          prop: 'exception_category_name',
          label: '巡查分类',
          align: 'center',
          showOverflowTooltip: true,
          width: 100
        },
        {
          prop: 'address',
          label: '异常地址',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120
        },
        {
          prop: 'organization_show',
          label: '单位可见',
          align: 'center',
          showOverflowTooltip: true,
          width: 100,
          slot: 'organization_show'
        },
        {
          prop: 'penalty',
          label: '是否处罚',
          align: 'center',
          showOverflowTooltip: true,
          width: 100,
          slot: 'penalty'
        },
        {
          prop: 'create_user',
          label: '上报用户',
          align: 'center',
          minWidth: 100,
          showOverflowTooltip: true
        },
        {
          prop: 'create_time',
          label: '上报时间',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 160,
          formatter: (row, column, cellValue) => {
            return this.$util.toDateString(cellValue);
          }
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 220,
          align: 'center',
          resizable: false,
          slot: 'action',
          //fixed: "right"
        }
      ],
      where: {},
      selection: [],
      current: {},
      dialog: {
        url: '/operation/info',
        visible: false,
        columns: [],
        no: '',
      },
      pushDialog: {
        visible: false,
        loading: false,
        user: []
      },
      verifyUserList: [],
      report_day    : {
        loading: false,
        show: false,
        data: {}
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    let arr = to.path.split('/')
    next((vm) => {
      vm.type = arr[arr.length - 1]
      vm.where.type = vm.type
      let col = JSON.parse(JSON.stringify(vm.columnsReset))
      if (vm.type === 'illegal') {
        col.splice(9, 0, {
              prop: 'is_verify',
              label: '是否审核',
              align: 'center',
              showOverflowTooltip: true,
              width: 100,
              slot: 'is_verify'
            },
            {
              prop: 'verify_user_name',
              label: '审核人',
              align: 'center',
              minWidth: 100,
              showOverflowTooltip: true
            })
        vm.initLoad = true
      }
      vm.columns = col
      vm.reload()
    })
  },
  // mounted() {
  //   this.report_day_tap()
  // },
  methods: {
    reload() {
      if (this.$refs.table) {
        this.$refs.table.reload({where: this.where})
      } else {
        setTimeout(this.reload, 10)
      }
    },
    reset() {
      this.where = {type: this.type}
      this.reload()
    },
    push(row) {
      this.current = row
      this.pushDialog.visible = true
      this.pushDialog.loading = false
      this.verifyUserList = []
      this.$http.post('/operation/getPushUser?id=' + row.id).then(res => {
        if (res.data.data && res.data.data.length > 0) {
          res.data.data.forEach(e => {
            this.verifyUserList.push({id: e.id, realname: e.realname, openid: e.openid})
          })
        }
      })
    },
    pushMsg() {
      this.pushDialog.loading = true
      this.$http.post('/operation/pushMsg', {id: this.current.id, user: this.pushDialog.user}).then(res => {
        this.pushDialog.loading = false
        if (res.data.data) {
          for (let item of res.data.data) {
            this.$notify({
              type: 'success',
              title: item.user,
              message: item.msg,
              duration: 2000
            });
          }
          this.pushDialog.visible = false
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    info(row) {
      this.dialog.columns = JSON.parse(JSON.stringify(this.columns))
      this.dialog.columns.shift()
      this.dialog.columns.shift()
      this.dialog.columns.shift()
      this.dialog.columns.pop()
      this.dialog.columns.unshift({
        prop: 'id',
        label: '标记点编码',
        width: 120,
        align: 'center',
        showOverflowTooltip: true,
        fixed: "left"
      })
      this.dialog.columns.push({
        columnKey: 'readUser',
        label: '阅读状态',
        minWidth: 120,
        resizable: false,
        slot: 'readUser',
      })
      this.dialog.columns.push({
        columnKey: 'action',
        label: '操作',
        width: 80,
        align: 'center',
        resizable: false,
        slot: 'action',
      })
      if (this.type === 'illegal') {
        this.dialog.columns.splice(9, 0, {
          prop: 'credential',
              label: '凭据',
              align: 'center',
              minWidth: 120,
              slot: 'credential'
        })
      }
      this.dialog.no = row.operation_no
      if (this.$refs.infoTable) {
        this.$refs.infoTable.isLoading = true
        this.$refs.infoTable.data = []
      }
      this.dialog.visible = true
    },
    dialogOpen() {
      this.$refs.infoTable.reload()
    },
    openEdit(row) {
      let query = {}
      if (row) {
        query.no = row.operation_no
      }
      this.$router.push({
        path: '/operation/edit/' + this.type,
        query: query
      })
    },
    remove(row) {
      const loading = this.$loading({lock: true})
      this.$http.post('/operation/delete', {no: row.operation_no}).then(res => {
        loading.close()
        if (res.data.code === 0) {
          this.$message.success(res.data.msg)
          this.reload()
        } else {
          this.$message.error(res.data.msg)
        }
      }).catch(e => {
        loading.close()
        this.$message.error(e.message)
      })
    },
    removeBatch() {
      this.$confirm('确定要删除选中的数据吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({lock: true});
        this.$http.post('/operation/delete', {no: this.selection.map(d => d.operation_no)}).then(res => {
          loading.close()
          if (res.data.code === 0) {
            this.$message({type: 'success', message: res.data.msg})
            this.reload()
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
          loading.close()
          this.$message.error(e.message)
        });
      }).catch(() => {
      })
    },
    setShowBatch() {
      this.$confirm('确定要把选中的数据设置为可见吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({lock: true})
        this.$http.post('/operation/setShow', {id: this.selection.map(d => d.operation_no)}).then(res => {
          loading.close()
          if (res.data.code === 0) {
            this.$message({type: 'success', message: res.data.msg})
            this.reload()
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
          loading.close()
          this.$message.error(e.message)
        })
      }).catch(() => {
      })
    },
    fetchImageAsBase64(imageUrl) {
      return fetch(imageUrl)
          .then(response => response.blob()) // 获取Blob对象
          .then(blob => {
            return new Promise((resolve, reject) => {
              const reader = new FileReader();
              reader.onload = function() {
                resolve(reader.result); // 这是Base64编码的字符串
              };
              reader.onerror = reject;
              reader.readAsDataURL(blob);
            });
          })
          .catch(error => {
            console.error('Error fetching image:', error);
            throw error;
          });
    },
    report_day_tap() {
      this.report_day.loading = true
      this.$http.post('/vv.report/day').then(async r => {
        const res = r.data.data
        for (let i in res.items) {
          for (let j in res.items[i].images) {
            res.items[i].images[j] = await this.fetchImageAsBase64(res.items[i].images[j])
          }
        }
        this.report_day.data = r.data.data
        this.report_day.show = true
        setTimeout(() => {
          const element = document.getElementById("day-pdf");
          const opt = {
            margin: 1,
            filename: "龙华区无人机自动化安全巡查工作日报.pdf",
            image: { type: "jpeg", quality: 0.98 },
            html2canvas: { scale: 2 },
            jsPDF: {
              unit: "in",
              format: "letter",
              orientation: "portrait",
            },
          };
          html2pdf().set(opt).from(element).save()
          this.report_day.show = false
          this.report_day.loading = false
        }, 111)
      })
    },
    report_week_tap() {
      this.$http.get('/vv.report/week',{responseType:'blob'}).then(r => fs.saveAs(r.data, '周报.docx'))
    }
  }
}
</script>

<style>
#day-pdf .el-descriptions__body {
  background-color: rgba(0,0,0,0);
  color: #000;
}
.pdf-bg {
  padding: 8px;
  background: url("~@/assets/bg-report.png") no-repeat;
}
</style>
